package com.toocms.jinjuhang.ui.index

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.SectionLayout
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.data.index.IndexData
import com.toocms.jinjuhang.data.index.RecGoodsData
import com.toocms.jinjuhang.utils.RuleSkip
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.base.MultiItemViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent

class IndexModel(application: Application) : BaseViewModel<BaseModel>(application) {
    private var p = 1
    val items = ObservableArrayList<MultiItemViewModel<*>>()
    val itemBinding = ItemBinding.of<MultiItemViewModel<*>> { binding, _, item ->
        when (item.itemType) {
            Constants.RecyclerViewItemType.ITEM_TYPE_ONE -> binding.set(
                BR.indexBannerItemModel, R.layout.item_index_banner
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_TWO -> binding.set(
                BR.indexNavigationItemModel, R.layout.item_index_navigation
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_THREE -> binding.set(
                BR.indexMessageItemModel, R.layout.item_index_message
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_FOUR -> binding.set(
                BR.indexModuleOneItemModel, R.layout.item_index_module_one
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_FIVE -> binding.set(
                BR.indexModuleTwoItemModel, R.layout.item_index_module_two
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_SIX -> binding.set(
                BR.indexModuleThreeItemModel, R.layout.item_index_module_three
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_SEVEN -> binding.set(
                BR.indexTitleItemModel, R.layout.item_index_title
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_EIGHT -> binding.set(
                BR.indexCommunityItemModel, R.layout.item_index_community
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_NINE -> binding.set(
                BR.indexTitleCenterItemModel, R.layout.item_index_title_center
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_TEN -> binding.set(
                BR.indexRecommendCommodityItemModel, R.layout.item_index_recommend_commodity
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_ZERO -> binding.set(
                BR.indexCommodityItemModel, R.layout.item_index_commodity
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_ELEVEN -> binding.set(
                BR.indexModuleFourItemModel, R.layout.item_index_module_four
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_TWELVE -> binding.set(
                BR.indexModuleFiveItemModel, R.layout.item_index_module_five
            )

            Constants.RecyclerViewItemType.ITEM_TYPE_THIRTEEN -> binding.set(
                BR.indexModuleSixItemModel, R.layout.item_index_module_six
            )
        }
    }
    val spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int) = when (items[position].itemType) {
            Constants.RecyclerViewItemType.ITEM_TYPE_ONE -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_TWO -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_THREE -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_FOUR -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_FIVE -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_SIX -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_SEVEN -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_EIGHT -> 4
            Constants.RecyclerViewItemType.ITEM_TYPE_NINE -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_TEN -> 3
            Constants.RecyclerViewItemType.ITEM_TYPE_ELEVEN -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_TWELVE -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_THIRTEEN -> 12
            Constants.RecyclerViewItemType.ITEM_TYPE_ZERO -> 6
            else -> 0
        }
    }
    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()
    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh()
    })
    val loadBindingCommand = BindingCommand<BindingAction>(this::loadRec)

    init {
        refresh(true)
    }

    private fun bindData(data: IndexData) {
        items.clear()
        //轮播图
        data.banners?.apply {
            if (isEmpty()) return@apply
            items += IndexBannerItemModel(this@IndexModel, this)
        }
        //资讯
        data.notice?.apply {
            if (isEmpty()) return@apply
            items += IndexMessageItemModel(this@IndexModel, this)
        }
        //导航
        data.navs?.apply {
            if (isEmpty()) return@apply
            items += IndexNavigationItemModel(this@IndexModel, this)
        }
        //模块
        data.section?.apply {
            if (isEmpty()) return@apply
            forEach { sectionItem ->
                var sectionLayout = SectionLayout.code2Layout(sectionItem.layout) ?: return@forEach
                if (sectionLayout.imageNumber > sectionItem.configure?.size ?: 0) return@forEach
                if (!TextUtils.isEmpty(sectionItem.title)) {
                    items += IndexTitleItemModel(
                        this@IndexModel,
                        ObservableField(sectionItem.title),
                        BindingCommand<BindingAction>(BindingAction {
                            RuleSkip.skip(
                                sectionItem.section_target_rule, sectionItem.section_param
                            )
                        })
                    )
                }
                when (sectionLayout) {
                    SectionLayout.SINGLE -> items += IndexModuleOneItemModel(
                        this@IndexModel, sectionItem.configure!!
                    )

                    SectionLayout.LEFT_ONE_RIGHT_ONE -> items += IndexModuleSixItemModel(
                        this@IndexModel, sectionItem.configure!!
                    )

                    SectionLayout.LEFT_ONE_RIGHT_TWO -> items += IndexModuleTwoItemModel(
                        this@IndexModel, sectionItem.configure!!
                    )

                    SectionLayout.LEFT_TWO_RIGHT_TWO -> items += IndexModuleThreeItemModel(
                        this@IndexModel, sectionItem.configure!!
                    )

                    SectionLayout.LEFT_TWO_RIGHT_ONE -> items += IndexModuleFourItemModel(
                        this@IndexModel, sectionItem.configure!!
                    )

                    SectionLayout.HORIZONTAL_THREE -> items += IndexModuleFiveItemModel(
                        this@IndexModel, sectionItem.configure!!
                    )

                    else -> {}
                }
            }
        }
        //公益
        data.igoods?.apply {
            if (isEmpty()) return@apply
            forEach { item ->
                if (!TextUtils.isEmpty(item.title)) {
                    items += IndexTitleItemModel(
                        this@IndexModel,
                        ObservableField(item.title),
                        BindingCommand<BindingAction>(BindingAction {
                            RuleSkip.skip(
                                item.target_rule, item.param
                            )
                        })
                    )
                }
                item.goods?.forEachIndexed { index, commodityItem ->
                    items += IndexRecommendCommodityItemModel(
                        this@IndexModel, ObservableField(commodityItem), index
                    )
                }
            }
        }
        //推荐
//        data.rec_goods?.apply {
//            if (isEmpty()) return
//            items += IndexTitleCenterItemModel(
//                this@IndexModel,
//                ObservableField(StringUtils.getString(R.string.str_unlimited_health))
//            )
//            forEachIndexed { index, recCommodityItem ->
//                items += IndexCommodityItemModel(
//                    this@IndexModel, ObservableField(recCommodityItem), index
//                )
//            }
//        }
    }

    private fun refresh(isShowLoading: Boolean = false) {
        requestData(Urls.Index.INDEX,
            resultClass = IndexData::class.java,
            isShowLoading = isShowLoading,
            result = {
                bindData(it)
            },
            finish = {
                refreshRec()
            })
    }

    private fun refreshRec() {
        p = 1
        recGoods(p)
    }

    private fun loadRec() {
        p++
        recGoods(p)
    }

    private fun recGoods(p: Int) {
        requestData(Urls.Index.REC_GOODS,
            mapOf(Pair("p", p.toString())),
            resultClass = RecGoodsData::class.java,
            result = {
                val list = it.list
                if (1 == p && !list.isNullOrEmpty()) {
                    items += IndexTitleCenterItemModel(
                        this@IndexModel,
                        ObservableField(StringUtils.getString(R.string.str_unlimited_health))
                    )
                }
                list?.forEachIndexed { index, recCommodityItem ->
                    items += IndexCommodityItemModel(
                        this@IndexModel, ObservableField(recCommodityItem), index
                    )
                }
            },
            finish = {
                stopRefreshOrLoadSingleLiveEvent.call()
            })
    }

}